package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.huewu.pla.lib.MultiColumnListView;

import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.dialog.ConnectionErrorDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.GridViewArrayAdapter;

public class BestGridView extends LinearLayout {

	private static int mLastUserId = -1;
	private static int UPDATE_TIME = 180000;

	private MainActivity mContext;
	private PullToRefreshGridView2 mPullRefreshGridView;
	private MultiColumnListView mGridView;
	private GridViewArrayAdapter mAdapter;
	private Timer mTimer;
	private boolean isPadding = false;
	private TextView mTxtTitle;
	private LinearLayout mMainMenu;
	public BestGridView(MainActivity context) {
		super(context);
		this.mContext = context;

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (inflater != null) {
			inflater.inflate(R.layout.product_gridview, this);
		}

		int numCol = (int) getResources().getDimension(R.dimen.grid_column);
		if (numCol == 2 || mContext.mScreenWidth > 1500) {
			numCol = 2;
			isPadding = true;
		} else
			numCol = 1;
		mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
		mTxtTitle = (TextView) findViewById(R.id.main_title);
		mPullRefreshGridView = (PullToRefreshGridView2) this
				.findViewById(R.id.productGridView_grid);
		mPullRefreshGridView.setMode(Mode.PULL_FROM_END);
		mGridView = mPullRefreshGridView.getRefreshableView();
		if (isPadding)
			mGridView.setPadding(0, 1, 1, 0);
		mGridView.setColumnCount(numCol);

		mAdapter = new GridViewArrayAdapter(mContext, mGridView.getId(), 0,
				mContext.mListProductBest, isPadding);
		mPullRefreshGridView.setAdapter(mAdapter);
		OnResume();
		mTxtTitle.setText(R.string.bestoftoday);
		mMainMenu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mContext.callMenu();
			}
		});
	}

	public void OnResume() {
		if (mContext.mUser == null) {
			mLastUserId = -1;
			if (mContext.mListProductBest.size() == 0) {
				GetProductTimer();
			}
			mAdapter = new GridViewArrayAdapter(mContext, mPullRefreshGridView.getId(), 0,
					mContext.mListProductBest, isPadding);
			mPullRefreshGridView.setAdapter(mAdapter);

		} else {

			if (mContext.mListProductBest.size() == 0
					|| mContext.mUser.Id != mLastUserId) {
				mLastUserId = mContext.mUser.Id;
				GetProductTimer();
			}
			mAdapter = new GridViewArrayAdapter(mContext, mPullRefreshGridView.getId(), 0,
					mContext.mListProductBest, isPadding);
			mPullRefreshGridView.setAdapter(mAdapter);
		}
	}

	public void GetProduct() {
		new CallServiceTask() {
			private ArrayList<Product> rs = new ArrayList<Product>();

			public void work() {
				try {
					rs = service.getBestOfDay(new Date(), mLastUserId);
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				if (rs == null || mContext == null || !MainActivity.isRunning)
					return;
				if (rs.size() == 0) {
					if (!mContext.isConnectionErrorShow) {
						mContext.isConnectionErrorShow = true;
						new ConnectionErrorDialog(mContext) {
							public void TryAgain() {
								GetProduct();
							};
						}.show();
					}
					return;
				} else {
					mContext.mListProductBest.clear();
					mContext.mListProductBest.addAll(rs);
					mAdapter.notifyDataSetChanged();
					mContext.SaveListBestToCache();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void GetProductTimer() {
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.w("Shopping", "Auto Update");
				new CallServiceTask() {
					private ArrayList<Product> rs = new ArrayList<Product>();

					public void work() {
						try {
							rs = service.getBestOfDay(new Date(), mLastUserId);
						} catch (IOException e) {
						} catch (XmlPullParserException e) {
						}
					};

					protected void onPostExecute(Void result) {
						if(!MainActivity.isRunning) return;
						if (rs == null)
							return;
						if (rs.size() == 0) {
							if (!mContext.isConnectionErrorShow) {
								mContext.isConnectionErrorShow = true;
								new ConnectionErrorDialog(mContext) {
									public void TryAgain() {
										GetProduct();
									};
								}.show();
							}
						} else {
							mContext.mListProductBest.clear();
							mContext.mListProductBest.addAll(rs);
							mAdapter.notifyDataSetChanged();
							mContext.SaveListBestToCache();
						}
					};
				}.execute();
			}
		}, 0, UPDATE_TIME);
		Log.w("Shopping", "Start Timer Best Of Day");
	}
}
